<template>
  <div class="container">
    <a-card title="用户管理" :bordered="false">
      <a-row style="margin-bottom: 16px">
        <a-col :span="16">
          <a-space>
            <a-button type="primary" @click="handleCreate">
              <template #icon><icon-plus /></template>
              新建用户
            </a-button>
          </a-space>
        </a-col>
        <a-col :span="8" style="text-align: right">
          <a-input-search
            placeholder="输入用户名搜索"
            style="width: 240px"
            @search="handleSearch"
          />
        </a-col>
      </a-row>

      <a-table
        :columns="columns"
        :data="userList"
        :loading="loading"
        :pagination="pagination"
        row-key="id"
        @page-change="handlePageChange"
      >
        <template #roles="{ record }">
          <a-space>
            <a-tag v-for="role in record.roles" :key="role.id" color="blue">
              {{ role.roleName }}
            </a-tag>
          </a-space>
        </template>
        <template #status="{ record }">
          <a-tag :color="record.status === 0 ? 'green' : 'red'">
            {{ record.status === 0 ? '正常' : '禁用' }}
          </a-tag>
        </template>
        <template #createdAt="{ record }">
          {{ formatDateTime(record.createdAt) }}
        </template>
        <template #actions="{ record }">
          <a-space>
            <a-button type="text" size="small" @click="handleEdit(record)">
              <template #icon><icon-edit /></template>
              编辑
            </a-button>
            <a-popconfirm
              content="确定要删除这个用户吗？"
              @ok="handleDelete(record.id)"
            >
              <a-button type="text" status="danger" size="small">
                <template #icon><icon-delete /></template>
                删除
              </a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </a-table>
    </a-card>

    <a-modal
      v-model:visible="modalVisible"
      :title="isEditMode ? '编辑用户' : '新建用户'"
      width="600px"
      @ok="handleModalOk"
      @cancel="handleModalCancel"
      :on-before-ok="submitForm"
    >
      <a-form ref="formRef" :model="form">
        <a-form-item
          field="username"
          label="用户名"
          :rules="[{ required: true, message: '请输入用户名' }]"
          :disabled="isEditMode"
        >
          <a-input v-model="form.username" />
        </a-form-item>
        <a-form-item
          v-if="!isEditMode"
          field="password"
          label="密码"
          :rules="[{ required: true, message: '请输入密码' }]"
        >
          <a-input-password v-model="form.password" />
        </a-form-item>
        <a-form-item field="fullName" label="姓名">
          <a-input v-model="form.fullName" />
        </a-form-item>
        <a-form-item v-if="isEditMode" field="status" label="状态">
          <a-radio-group v-model="form.status">
            <a-radio :value="0">正常</a-radio>
            <a-radio :value="1">禁用</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item
          field="roleIds"
          label="分配角色"
          :rules="[{ required: true, message: '请至少选择一个角色' }]"
        >
          <a-select
            v-model="form.roleIds"
            placeholder="请选择角色"
            multiple
            :loading="roleLoading"
          >
            <a-option
              v-for="role in allRoles"
              :key="role.id"
              :value="role.id"
              :label="role.roleName"
            />
          </a-select>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import {
  listUsersApi,
  createUserApi,
  updateUserApi,
  deleteUserApi
} from '@/api/user'
import { getAllRolesApi } from '@/api/role'
import type { UserDetail, UserCreateRequest, UserUpdateRequest } from '@/types/api/user'
import type { Role } from '@/types/api/role'
import { Message, type FormInstance } from '@arco-design/web-vue'
import {
  IconPlus,
  IconEdit,
  IconDelete
} from '@arco-design/web-vue/es/icon'

// -- 状态定义 --
const loading = ref(false)
const userList = ref<UserDetail[]>([])
const searchKeyword = ref('')

// 分页
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showTotal: true
})

// 弹窗
const modalVisible = ref(false)
const isEditMode = ref(false)
const formRef = ref<FormInstance | null>(null)
const currentEditId = ref<number | null>(null)

// 弹窗内的表单
type FormModel = Partial<UserCreateRequest & UserUpdateRequest>
const defaultForm: FormModel = {
  username: '',
  password: '',
  fullName: '',
  status: 0,
  roleIds: []
}
const form = reactive<FormModel>({ ...defaultForm })

// 角色列表 (用于下拉框)
const roleLoading = ref(false)
const allRoles = ref<Role[]>([])

// -- 表格列定义 --
const columns = [
  { title: 'ID', dataIndex: 'id', width: 80 },
  { title: '用户名', dataIndex: 'username' },
  { title: '姓名', dataIndex: 'fullName' },
  { title: '角色', slotName: 'roles' },
  { title: '状态', slotName: 'status' },
  { title: '创建时间', slotName: 'createdAt' },
  { title: '操作', slotName: 'actions', width: 180, align: 'center' }
]

// -- API 调用 --
const fetchUsers = async () => {
  loading.value = true
  try {
    const params = {
      current: pagination.current,
      pageSize: pagination.pageSize,
      username: searchKeyword.value || undefined
    }
    const data = await listUsersApi(params)
    console.log(data)
    userList.value = data.records
    pagination.total = data.total
  } catch (error) {
    Message.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

// 获取所有角色，用于弹窗下拉框
const fetchAllRoles = async () => {
  roleLoading.value = true
  try {
    allRoles.value = await getAllRolesApi()
  } catch (error) {
    Message.error('获取角色列表失败')
  } finally {
    roleLoading.value = false
  }
}

// -- 生命周期钩子 --
onMounted(() => {
  fetchUsers()
  fetchAllRoles() // 提前加载
})

// -- 事件处理 --
const formatDateTime = (isoString: string) => {
  if (!isoString) return 'N/A'
  return new Date(isoString).toLocaleString()
}

const handlePageChange = (page: number) => {
  pagination.current = page
  fetchUsers()
}

const handleSearch = (keyword: string) => {
  searchKeyword.value = keyword
  pagination.current = 1 // 搜索时重置到第一页
  fetchUsers()
}

const resetForm = () => {
  Object.assign(form, defaultForm)
  currentEditId.value = null
  formRef.value?.clearValidate()
}

const handleCreate = () => {
  resetForm()
  isEditMode.value = false
  modalVisible.value = true
}

const handleEdit = (record: UserDetail) => {
  resetForm()
  isEditMode.value = true
  currentEditId.value = record.id
  // 填充表单
  form.username = record.username
  form.fullName = record.fullName
  form.status = record.status
  form.roleIds = record.roles.map((role) => role.id) // 提取 role id
  modalVisible.value = true
}

const handleDelete = async (id: number) => {
  try {
    await deleteUserApi(id)
    Message.success('删除成功')
    await fetchUsers() // 刷新列表
  } catch (error) {
    Message.error('删除失败')
  }
}

const handleModalCancel = () => {
  modalVisible.value = false
  resetForm()
}

// 弹窗表单提交
const submitForm = async () => {
  const validateError = await formRef.value?.validate()
  if (validateError) {
    return false // 阻止弹窗关闭
  }

  try {
    if (isEditMode.value && currentEditId.value) {
      // 编辑模式
      await updateUserApi(currentEditId.value, {
        fullName: form.fullName,
        status: form.status,
        roleIds: form.roleIds
      } as UserUpdateRequest)
      Message.success('更新成功')
    } else {
      // 新建模式
      await createUserApi(form as UserCreateRequest)
      Message.success('创建成功')
    }
    await fetchUsers() // 刷新列表
    return true // 允许弹窗关闭
  } catch (error) {
    Message.error('操作失败')
    return false // 阻止弹窗关闭
  }
}

const handleModalOk = () => {
  handleModalCancel()
}
</script>

<style scoped>
.container {
  padding: 20px;
}
</style>
